#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/8/1  17:49
# @Author: 余浪人
# @email: yulangren520@gmail.com
from flask import jsonify
from apps import get_sys_url
from apps.lib.public import get_date_str, get_uuid16
from apps.control.file_view import qiNiu_upload
import os, re, requests


def apiErrors(obj):
    '''
    验证数据合法性
    :param obj: 查询对象
    :return:
    '''
    if obj is None:
        return jsonify({"status": 400, "message": "数据有误,验证失败!"})


def save_webImg(url):
    '''
    网络图片本地化
    :param path:  保存目录
    :return: url
    '''
    error = ''
    relative_path = os.path.join('images/', get_date_str(),  get_uuid16() + '.' + url.split('.')[-1]).replace('\\','/')
    try:
        response = requests.get(url,headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'})
        path = qiNiu_upload(relative_path, response.content)
        if path and isinstance(path,str): return path
    except:
        return


def save_img(html: str):
    pic_url = re.findall('<img.*src="(.*?\..*?)"', html)  # url 列表
    content = html
    for url in pic_url:
        img_url = re.sub(r'\\', '/', save_webImg(url))
        content = content.replace(url, img_url)
    return content
